package com.tzm.lucene.test01;

import org.apache.lucene.document.Document;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.*;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;

import java.io.IOException;
import java.nio.file.Paths;

/**
 * 查询索引的步骤：
 *
 *  1. 创建一个Directory对象，指定索引库的位置
 *  2. 创建一个IndexReader对象
 *  3. 创建一个IndexSearcher对象，构造方法中的参数IndexReader对象
 *  4. 创建一个Query对象， TermQuery
 *  5. 执行查询，得到一个TopDocs对象
 *  6. 取查询结果的总记录数
 *  7. 取文档列表
 *  8. 打印文档中的内容
 *  9. 关闭IndexReader对象
 */

public class Searcher {

    public static void main(String[] args) throws IOException {
        Directory indexDir = FSDirectory.open(Paths.get("D:\\temp\\index"));
        IndexReader indexReader = DirectoryReader.open(indexDir);
        IndexSearcher indexSearcher = new IndexSearcher(indexReader);
        Query query = new TermQuery(new Term("content", "good"));
        TopDocs topDocs = indexSearcher.search(query, 10);
        System.out.println("总记录数: " + topDocs.totalHits);
        ScoreDoc[] scoreDocs = topDocs.scoreDocs;
        for (ScoreDoc scoreDoc : scoreDocs) {
            int docId = scoreDoc.doc;
            Document document = indexSearcher.doc(docId);
            System.out.println(document.get("name"));
            System.out.println(document.get("path"));
            System.out.println(document.get("content"));
            System.out.println(document.get("size"));
            System.out.println("--------------------------");
        }
        indexReader.close();

    }
}
